package com.sky.controller.admin;

import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.rmi.server.RemoteRef;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@RestController
@Slf4j
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @PostMapping
    @ApiOperation("增加菜品")
    public Result<Object> add(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO.getName());

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishService.add(dish);

        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(item -> {
                item.setDishId(dishId);
            });
            dishService.addFlavor(flavors);
        }

        cleanCache("dish_" + dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> queryPage(DishPageQueryDTO dishPageQueryDTO) {
        log.info("菜品分页查询");
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        PageResult page = dishService.queryPage(dishPageQueryDTO);
        return Result.success(page);
    }


    @DeleteMapping
    @ApiOperation("批量删除")
    public Result<Object> deleteByIds(@RequestParam List<Long> ids) {
        log.info("删除id为：{} 的菜品", ids);
        // 查询是否有已经起售
        if(dishService.hasStatus(ids)) {
            return Result.error("删除失败，删除名单中有已起售的菜品");
        }
        // 查看是否有关联的套餐
        if(dishService.hasSetMeal(ids)) {
            return Result.error("删除失败，删除名单中有关联套餐的菜品");
        }
        // 删除菜品
        dishService.deleteDish(ids);

        // 删除关联口味
        dishService.deleteFlavor(ids);

        cleanCache("dish_*");
        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用菜品")
    public Result<Object> editStatus(@PathVariable Integer status, Long id) {
        log.info("{} id为 {} 的菜品", status == 1?"启用":"禁用", id);
        if (status == 0 && dishService.isOwnSetMeal(id)) {
            return Result.error("该彩菜品被一个或多个已启用的套餐关联");
        }
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishService.setStatus(dish);

        DishVO dishVO = dishService.getByIdForDishVO(id);
        cleanCache("dish_" + dishVO.getCategoryId());
        return Result.success();
    }

    @ApiOperation("查询菜品及口味")
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id) {
        log.info("通过id查找菜品和口味");
        return Result.success(dishService.getByIdForDishVO(id));
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result<Object> uploadDish(@RequestBody DishVO dishVO) {
        log.info("修改id为：{} 的菜品", dishVO.getId());

        // 查找之前的菜品
        DishVO oldDish = dishService.getByIdForDishVO(dishVO.getId());
        cleanCache("dish_" + oldDish.getCategoryId());

        // 修改
        dishService.updateDishAndFlavor(dishVO);

        // 如果菜品类别也被更改
        if (!Objects.equals(dishVO.getCategoryId(), oldDish.getCategoryId()))
            cleanCache("dish_" + dishVO.getCategoryId());
        return Result.success();
    }

    @GetMapping("list")
    @ApiOperation("根据分类id查询菜品列表")
    public Result<List<Dish>> list(Integer categoryId) {
        log.info("查询分类id为：{}的菜品", categoryId);
        return Result.success(dishService.getByCategoryId(categoryId));
    }

    private void cleanCache(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        if(keys != null) {
            redisTemplate.delete(keys);
        }
    }
}
